#include "get_logkey.hpp"

void add_key(List_Key* list,string k)
{
  if(!key_is_present(list,k))
    {
      List_Key* l=list;

      while(l->next != NULL)
	l=l->next;

      l->next=new List_Key;
      l->next->key=k;
      l->next->next=NULL;
    }
}

bool key_is_present(List_Key* list,string k)
{
  bool r_find(false);
  List_Key* l=list;

  while(l != NULL && !r_find)
    {
      if(l->key.compare(k) == 0)
	r_find=true;

      l=l->next;
    }

  return r_find;
}

void delete_all(List_Key* list)
{
  List_Key* l=list;

  while(list != NULL)
    {
      l=list;
      list=list->next;
      delete l;
    }
}

void print_list(List_Key* l)
{
  List_Key* le=l;
  int cpt(0);

  while(le != NULL)
    {
      cout << cpt << " : " << le->key << " END" << endl;
      le=le->next;
      ++cpt;
    }
}

void read(FILE* f, List_Key* list)
{
  int cara(42);
  bool begin_lign(true);
  bool key_word(true);
  string key("");

  while(cara != EOF)
    {
      if(begin_lign)
	{
	  for(int c=0 ; c < 7 ; ++c)
	    cara=fgetc(f);
	  begin_lign=false;
	}

      if((char)cara == ':')
	{
	  key_word=false;
	  add_key(list,key);
	  key="";
	}

      if(key_word)
	key+=(char)cara;

      if((char)cara == '\n')
	{
	  begin_lign=true;
	  key_word=true;
	  key="";
	}

      cara=fgetc(f);
    }
}

void save(List_Key* list)
{
  string file(OUTPUT_FILE);
  FILE* f=fopen(file.c_str(),"a+");
  List_Key* l=list;
  string lign;

  while(l != NULL)
    {
      lign=l->key+'\n';
      fwrite(lign.c_str(),sizeof(char),lign.length(),f);
      l=l->next;
    }

  fclose(f);
}

int main(void)
{
  List_Key* l=new List_Key;
  l->key="";
  l->next=NULL;

  string file(FOLDER_LOG);
  file+=FILE_LOG;
  FILE* f=fopen(file.c_str(),"r");

  fseek(f,0,SEEK_SET);
  read(f,l);

  cout << "LIST" << endl;
  print_list(l);
  save(l);

  delete_all(l);
  fclose(f);

  return 0;
}
